package com.letian.web.controller.system;

import java.util.List;
import java.util.Set;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.letian.common.config.WxConfig;
import com.letian.common.core.domain.model.UsersVO;
import com.letian.common.core.domain.model.WxLoginBody;
import com.letian.common.utils.StringUtils;
import com.letian.common.utils.http.WechatUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.letian.common.constant.Constants;
import com.letian.common.core.domain.AjaxResult;
import com.letian.common.core.domain.entity.SysMenu;
import com.letian.common.core.domain.entity.SysUser;
import com.letian.common.core.domain.model.LoginBody;
import com.letian.common.utils.SecurityUtils;
import com.letian.framework.web.service.SysLoginService;
import com.letian.framework.web.service.SysPermissionService;
import com.letian.system.service.ISysMenuService;

/**
 * 登录验证
 *
 * @author letian
 */
@RestController
public class SysLoginController {
    @Autowired
    private SysLoginService loginService;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    WxConfig wxConfig;


    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody) {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    @PostMapping("/wx/login")
    public AjaxResult user_login(@RequestBody WxLoginBody body) {    // 用户非敏感信息：rawData
        // 签名：signature
//        JSONObject rawDataJson = JSON.parseObject(body.getRawData());    // 1.接收小程序发送的code
        // 2.开发者服务器 登录凭证校验接口 appi + appsecret + code
        JSONObject SessionKeyOpenId = WechatUtil.getSessionKeyOrOpenId(body.getCode(), wxConfig);    // 3.接收微信接口服务 获取返回的参数
        String errcode = SessionKeyOpenId.getString("errcode");
        if(StringUtils.isNotBlank(errcode)){
            return AjaxResult.error("登录验证失败");
        }
        String openid = SessionKeyOpenId.getString("openid");
        String sessionKey = SessionKeyOpenId.getString("session_key");    // 4.校验签名 小程序发送的签名signature与服务器端生成的签名signature2 = sha1(rawData + sessionKey)
//        String signature2 = DigestUtils.sha1Hex(body.getRawData() + sessionKey);
//        if (!signature2.equals(body.getSignature())) {
//            return AjaxResult.error("签名校验失败");
//        }
        // 5.根据返回的User实体类，判断用户是否是新用户，是的话，将用户信息存到数据库；
        UsersVO usersVO = new UsersVO();
        String nickName = "微信用户";
        String avatarUrl = "";
        String sex =  "2";
        usersVO.setUserName(openid);
        usersVO.setAvatar(avatarUrl);
        usersVO.setNickName(nickName);
        usersVO.setSex(sex);
        usersVO.setOpenId(openid);
        usersVO.setRoleId(Constants.COMMON_ROLE);
        String token = loginService.loginWx(usersVO);
        AjaxResult ajax = AjaxResult.success();
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public AjaxResult getInfo() {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public AjaxResult getRouters() {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return AjaxResult.success(menuService.buildMenus(menus));
    }
}
